﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Web;
using System.IO;
using System.Drawing;
using System.Web.UI.WebControls;

namespace Comm
{
    /// <summary>
    /// 图片类
    /// </summary>
    public class Dispose_Image
    {
        /// <summary>
        /// 错误描述
        /// </summary>
        public string error = "";
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="filepath">原文件路径</param>
        /// <param name="directory ">文件保存目录</param>
        /// <returns>保存文件全路径(上传失败：返回空)</returns>
        public string upLoadImage(FileUpload fileupload, string directory)
        {
            if (fileupload == null || fileupload.PostedFile.FileName.Trim() == "")
            {
                error = "原路径不存在";
                return "";
            }
            string filepath = fileupload.PostedFile.FileName.Trim();
            if (!check_ExtendName(filepath))
            {
                error = "该文件不是图片格式的文件";
                return "";
            }
            if (!Directory.Exists(HttpContext.Current.Server.MapPath(directory))) Directory.CreateDirectory(HttpContext.Current.Server.MapPath(directory));
            directory += "/" + DateTime.Now.ToString("yyyyMMddHHmmss") + new Random().Next(1000) + Path.GetExtension(filepath);

            System.Drawing.Image img = null;
            try
            {
                img = System.Drawing.Image.FromStream(fileupload.PostedFile.InputStream);
                img.Save(HttpContext.Current.Server.MapPath(directory));
                img.Dispose();
                return directory;
            }
            catch
            {
                error = "该文件损坏或丢失";
                return "";
            }
        }


        /// <summary>
        /// 判断所选的文件是不是允许上传的文件
        /// </summary>
        /// <param name="extendName"></param>
        /// <returns></returns>
        private bool check_ExtendName(string filepath)
        {
            string extName = System.IO.Path.GetExtension(filepath);
            string[] extendNames = { ".jpg", ".jpge", ".gif", ".bmp", ".png" };
            foreach (string tempextName in extendNames)
            {
                if (tempextName.Trim().ToLower() == extName.Trim().ToLower())
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="SavePath">原图的完整路径</param>
        /// <param name="sThumb">缩略图名的文件夹名</param>
        /// <param name="sSavePath">生成缩略图的路径</param>
        /// <param name="intThumbWidth">缩略图的宽度</param>
        /// <param name="intThumbHeight">缩略图的高度</param>
        /// <param name="sextendName">缩略图的后缀名</param>
        /// <returns></returns>
        public string upLoadThumbnail1(string SavePath, string sSavePath, int intThumbWidth, int intThumbHeight)
        {
            //获取原始图片  
            System.Drawing.Image originalImage = System.Drawing.Image.FromFile(SavePath);
            //缩略图画布宽高  
            int towidth = intThumbWidth;
            int toheight = intThumbHeight;
            //原始图片写入画布坐标和宽高(用来设置裁减溢出部分)  
            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;
            //原始图片画布,设置写入缩略图画布坐标和宽高(用来原始图片整体宽高缩放)  
            int bg_x = 0;
            int bg_y = 0;
            int bg_w = towidth;
            int bg_h = toheight;
            ////倍数变量  
            //double multiple = 0;
            ////获取宽长的或是高长与缩略图的倍数  
            //if (originalImage.Width >= originalImage.Height)
            //    multiple = (double)originalImage.Width / (double)intThumbWidth;
            //else
            //    multiple = (double)originalImage.Height / (double)intThumbHeight;
            ////上传的图片的宽和高小等于缩略图  
            //if (ow <= intThumbWidth && oh <= intThumbHeight)
            //{
            //    //缩略图按原始宽高  
            //    bg_w = originalImage.Width;
            //    bg_h = originalImage.Height;
            //    //空白部分用背景色填充  
            //    bg_x = Convert.ToInt32(((double)towidth - (double)ow) / 2);
            //    bg_y = Convert.ToInt32(((double)toheight - (double)oh) / 2);
            //}
            ////上传的图片的宽和高大于缩略图  
            //else
            //{
            //    //宽高按比例缩放  
            //    bg_w = Convert.ToInt32((double)originalImage.Width / multiple);
            //    bg_h = Convert.ToInt32((double)originalImage.Height / multiple);
            //    //空白部分用背景色填充  
            //    bg_y = Convert.ToInt32(((double)intThumbHeight - (double)bg_h) / 2);
            //    bg_x = Convert.ToInt32(((double)intThumbWidth - (double)bg_w) / 2);
            //}
            //新建一个bmp图片,并设置缩略图大小.  
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);
            //新建一个画板  
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
            //设置高质量插值法  
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;
            //设置高质量,低速度呈现平滑程度  
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            //清空画布并设置背景色  
            g.Clear(System.Drawing.ColorTranslator.FromHtml("#F2F2F2"));
            //在指定位置并且按指定大小绘制原图片的指定部分  
            //第一个System.Drawing.Rectangle是原图片的画布坐标和宽高,第二个是原图片写在画布上的坐标和宽高,最后一个参数是指定数值单位为像素  
            g.DrawImage(originalImage, new System.Drawing.Rectangle(bg_x, bg_y, bg_w, bg_h), new System.Drawing.Rectangle(x, y, ow, oh), System.Drawing.GraphicsUnit.Pixel);
            string name = System.IO.Path.GetFileName(SavePath);
            string smallImagePath = System.Web.HttpContext.Current.Server.MapPath(string.Format("{0}/{1}", sSavePath, name));
            try
            {
                //获取图片类型  
                string fileExtension = System.IO.Path.GetExtension(SavePath).ToLower();
                //按原图片类型保存缩略图片,不按原格式图片会出现模糊,锯齿等问题.  
                switch (fileExtension)
                {
                    case ".gif": bitmap.Save(smallImagePath, System.Drawing.Imaging.ImageFormat.Gif); break;
                    case ".jpg": bitmap.Save(smallImagePath, System.Drawing.Imaging.ImageFormat.Jpeg); break;
                    case ".bmp": bitmap.Save(smallImagePath, System.Drawing.Imaging.ImageFormat.Bmp); break;
                    case ".png": bitmap.Save(smallImagePath, System.Drawing.Imaging.ImageFormat.Png); break;
                }
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }

            return "";
        }

        public string upLoadThumbnail(string SavePath, string sSavePath, int intThumbWidth, int intThumbHeight)
        {
            return upLoadThumbnail(SavePath, sSavePath, intThumbWidth, intThumbHeight, "Cut");
        }
        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="SavePath">原图的完整路径</param>
        /// <param name="sThumb">缩略图名的文件夹名</param>
        /// <param name="sSavePath">生成缩略图的路径</param>
        /// <param name="intThumbWidth">缩略图的宽度</param>
        /// <param name="intThumbHeight">缩略图的高度</param>
        /// <param name="sextendName">缩略图的后缀名</param>
        /// <returns></returns>
        public string upLoadThumbnail(string SavePath, string sSavePath, int intThumbWidth, int intThumbHeight, string mode)
        {

            string directory = System.IO.Path.GetDirectoryName(sSavePath);
            if (!Directory.Exists(System.Web.HttpContext.Current.Server.MapPath(directory)))
                Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath(directory));

            //string name = System.IO.Path.GetFileName(SavePath);
            //string smallImagePath = System.Web.HttpContext.Current.Server.MapPath(string.Format("{0}/{1}", sSavePath, name));
            //MagickNet.Image img = new MagickNet.Image(SavePath);

            //System.Drawing.Image image = System.Drawing.Image.FromFile(SavePath);
            //image.Dispose();
            //img.Resize(new System.Drawing.Size(intThumbWidth, intThumbHeight));
            //img.Write(smallImagePath);
            //MagickNet.Magick.Term();

            //return string.Format("{0}/{1}", sSavePath, name);

            System.Drawing.Image originalImage = System.Drawing.Image.FromFile(SavePath);

            int towidth = intThumbWidth;
            int toheight = intThumbHeight;

            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;

            switch (mode)
            {
                case "HW"://指定高宽缩放（可能变形）                
                    break;
                case "W"://指定宽，高按比例                    
                    toheight = originalImage.Height * intThumbWidth / originalImage.Width;
                    break;
                case "H"://指定高，宽按比例
                    towidth = originalImage.Width * intThumbHeight / originalImage.Height;
                    break;
                case "Cut"://指定高宽裁减（不变形）                
                    if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                    {
                        oh = originalImage.Height;
                        ow = originalImage.Height * towidth / toheight;
                        y = 0;
                        x = (originalImage.Width - ow) / 2;
                    }
                    else
                    {
                        ow = originalImage.Width;
                        oh = originalImage.Width * intThumbHeight / towidth;
                        x = 0;
                        y = (originalImage.Height - oh) / 2;
                    }
                    break;
                default:
                    break;
            }
            //使用MagickNet对图片进行处理，首先按指定大小比例对图片进行剪切，然后进行缩放，采用CUT方式
            MagickNet.Image img = new MagickNet.Image(SavePath);
            img.Crop(new System.Drawing.Rectangle(x, y, ow, oh));
            img.Resize(new System.Drawing.Size(towidth, toheight));
            string name = System.IO.Path.GetFileName(SavePath);
            string path = System.Web.HttpContext.Current.Server.MapPath(string.Format("{0}/{1}", sSavePath, name));
            img.Write(path);
            MagickNet.Magick.Term();
            originalImage.Clone();
            return string.Format("{0}/{1}", sSavePath, name);

        }
        public string upLoadThumbnail(HttpPostedFile file, string sSavePath, int intThumbWidth, int intThumbHeight)
        {
            return upLoadThumbnail(file, sSavePath, intThumbWidth, intThumbHeight, "Cut");
        }
        public string upLoadThumbnail(HttpPostedFile file, string sSavePath, int intThumbWidth, int intThumbHeight, string mode)
        {

            string directory = System.IO.Path.GetDirectoryName(sSavePath);
            if (!Directory.Exists(System.Web.HttpContext.Current.Server.MapPath(directory)))
                Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath(directory));

            //System.IO.Stream oStream = file.InputStream;
            System.Drawing.Image originalImage = System.Drawing.Image.FromStream(file.InputStream);

            int towidth = intThumbWidth;
            int toheight = intThumbHeight;

            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;

            switch (mode)
            {
                case "HW"://指定高宽缩放（可能变形）                
                    break;
                case "W"://指定宽，高按比例                    
                    toheight = originalImage.Height * intThumbWidth / originalImage.Width;
                    break;
                case "H"://指定高，宽按比例
                    towidth = originalImage.Width * intThumbHeight / originalImage.Height;
                    break;
                case "Cut"://指定高宽裁减（不变形）                
                    if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                    {
                        oh = originalImage.Height;
                        ow = originalImage.Height * towidth / toheight;
                        y = 0;
                        x = (originalImage.Width - ow) / 2;
                    }
                    else
                    {
                        ow = originalImage.Width;
                        oh = originalImage.Width * intThumbHeight / towidth;
                        x = 0;
                        y = (originalImage.Height - oh) / 2;
                    }
                    break;
                default:
                    break;
            }
            //使用MagickNet对图片进行处理，首先按指定大小比例对图片进行剪切，然后进行缩放，采用CUT方式
            MagickNet.Image img = new MagickNet.Image(file.InputStream);
            img.Crop(new System.Drawing.Rectangle(x, y, ow, oh));
            img.Resize(new System.Drawing.Size(towidth, toheight));
            string name = System.IO.Path.GetFileName(sSavePath);
            string path = System.Web.HttpContext.Current.Server.MapPath(string.Format("{0}", sSavePath));
            img.Write(path);
            MagickNet.Magick.Term();
            return sSavePath;

        }
    }
}
